package com.qfedu.controller;

import com.qfedu.entity.Animal;
import com.qfedu.entity.User;
import com.qfedu.service.intf.AnimalService;
import com.qfedu.service.intf.UserService;
import com.qfedu.vo.PageVo;
import com.qfedu.vo.R;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api/user/")
public class UserController {
    @Resource
    private UserService service;

    @PostMapping("add.do")
    public R add(User user){
        return service.save(user);
    }
    @PostMapping("update.do")
    public R update(User user){
        return service.update(user);
    }
    @PostMapping("del.do")
    public R del(int id){
        return service.delete(id);
    }
    @GetMapping("page.do")
    public PageVo page(String username,int page, int limit){
        return service.queryPage(username, page, limit);
    }
    /**实现txt文件的数据导入*/
    @PostMapping("upload.do")
    public R upload(MultipartFile file, HttpServletRequest request) throws IOException, IOException {
        //1.验证上传的文件是否为空
        if(file.isEmpty()){
            return R.fail();
        }else {
            //文件有内容
            //2.获取文件名称
            String fn=file.getOriginalFilename();
            //3.获取上传的文件内容
            byte[] data=file.getBytes();
            //4.存储上传的内容到服务器上 输出流
            //存储到发布路径  真实路径
            File f=new File(request.getServletContext().getRealPath("/"),fn);

            FileOutputStream fos=new FileOutputStream(f);
            fos.write(data);
            fos.close();

            return R.ok("http://localhost:8080/"+fn);
        }
    }
//   登录系统判断
    @RequestMapping(value = "login")
    public String form(@RequestParam("username") String username,
                       @RequestParam("password") String password,
                       Model model) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        User isLogin = service.logincheck(username,password);
        if (isLogin!=null){
            return "login.html";
        }else{
            return "index.html";
        }
    }
}
